package com.jerry.ReadWriteLock;

public class ReadLock implements Lock {
    private ReadWriteLock readWriteLock;

    public ReadLock(ReadWriteLock readWriteLock) {
        this.readWriteLock = readWriteLock;
    }

    @Override
    public void lock() {
        synchronized (readWriteLock.getMutex()){
            //如果当前正在写或者偏好写且有等待写，则将当前线程阻塞，如果阻塞异常，则直接执行下去
            while(readWriteLock.getWritingWriter() > 0 || ( readWriteLock.getPreferWrite()&&readWriteLock.getWaitingWriter() > 0)){
               try {
                   readWriteLock.getMutex().wait();
               }catch (Exception e){

               }
            }
            //如果符合条件则增加正在读
            this.readWriteLock.increaseReadingReader();

        }

    }

    @Override
    public void unlock() {
        synchronized (readWriteLock.getMutex()){
            this.readWriteLock.decreaseReadingReader();
            this.readWriteLock.changePrefer(true);
            this.readWriteLock.getMutex().notifyAll();
        }
    }
}
